<?php

class Project_model extends MY_Model {

    public function __construct() {
	parent::__construct();

	$this->table = 'jd_project';
    }

    public function records($limit, $offset, $conditions = array()) {
	$this->db->select('
            p.*,
            t.value as type_value,
            a.value as area_value,
            ph.file_name as cover_name,
            al.cover as album_cover
        ');

	$this->db->from($this->table . ' p');

	$this->db->join('jd_label t', 'p.type=t.id', 'left');
	$this->db->join('jd_label a', 'p.area=a.id', 'left');
	$this->db->join('jd_album al', 'p.album=al.id', 'left');
	$this->db->join('jd_photo ph', 'al.cover=ph.id', 'left');

	if (isset($conditions[0])) {
	    foreach ($conditions as $condition) {
		$prefix = (strpos($condition[0], '.') === false) ? 'p.' : '';
		$this->db->where($prefix . $condition[0], $condition[1]);
	    }
	}

	if ($limit) {
	    $this->db->limit($limit, $offset);
	}

	$this->db->order_by('p.order', 'desc');

	$query = $this->db->get();

	return $query->result();
    }

    public function total($conditions = array()) {
	$this->db->from($this->table . ' p');

	$this->db->join('jd_label t', 'p.type=t.id', 'left');
	$this->db->join('jd_label a', 'p.area=a.id', 'left');
	$this->db->join('jd_album al', 'p.album=al.id', 'left');
	$this->db->join('jd_photo ph', 'al.cover=ph.id', 'left');

	if (isset($conditions[0])) {
	    foreach ($conditions as $condition) {
		$prefix = (strpos($condition[0], '.') === false) ? 'p.' : '';
		$this->db->where($prefix . $condition[0], $condition[1]);
	    }
	}

	return $this->db->count_all_results();
    }

    public function order($id, $new_order) {
	$label = $this->find($id);

	if ($label->order > $new_order) {
	    $end_order = $label->order - 1;

	    $sql = "update `{$this->table}` 
            set `order`=`order`+1 
            where `order`>={$new_order} 
            and `order`<={$end_order};";
	} else {
	    $start_order = $label->order + 1;

	    $sql = "update `{$this->table}`
            set `order`=`order`-1 
            where `order`>='{$start_order}' 
            and `order`<='{$new_order}';";
	}

	$this->db->query($sql);

	return $this->update($id, array('order' => $new_order));
    }

    public function max_order() {
	$sql = "select max(`order`) as max_order from `{$this->table}`";

	$query = $this->db->query($sql);

	return $query->row_object()->max_order;
    }

}